//
//  GGTTeamBuyDetailViewController.m
//  GGT
//
//  Created by 空空空 on 14/10/29.
//  Copyright (c) 2014年 GGT. All rights reserved.
//

#import "GGTTeamBuyDetailViewController.h"
#import "DPRequest.h"
#import "GGTAppDelegate.h"
#import "UIImageView+WebCache.h"
#import "GGTTeamBuyDetailModel.h"
#import "GGTDeleteLabel.h"
#import "GGTBusinessDetailModel.h"
#import "GGTTeamBuyDetailTableViewCell.h"
#import "GGTTeamBuyReviewModel.h"
#import "GGTBusinessModel.h"
#import "GGTOtherTeamBuyTableViewCell.h"
#import "MBProgressHUD.h"
#import "GGTReviewTableViewCell.h"
#import "GGTBusinessTableViewCell.h"
#import "GGTOtherTeamBuyTableViewCell.h"
#import "GGTBusinessViewController.h"
#import "GGTHeadTableViewCell.h"
#import "GGTDataBaseHandler.h"
#import "GGTTeamBuyDataModel.h"
#import "GGTWebViewController.h"
@interface GGTTeamBuyDetailViewController ()<DPRequestDelegate, UITableViewDataSource, UITableViewDelegate, UITextViewDelegate, UIActionSheetDelegate>
@property (nonatomic, retain) NSMutableDictionary *GGTTeamBuy;//指定团购result
@property (nonatomic, assign) int flag;//解析标志位
@property (nonatomic, retain) NSDictionary *GGTTeamBuyBusiness;//商户字典
@property (nonatomic, retain) NSMutableArray *GGTTeamBuyReviews;//评价数组
@property (nonatomic, retain) NSDictionary *GGTTeamBuyBusinessStar;//星际评分
@property (nonatomic, retain) NSMutableArray *reviewArr;//
@property (nonatomic, retain) UITableView *reviewTableView;//
@property (nonatomic, retain) NSString *s1;//去掉“团购信息后的内容”
@property (nonatomic, retain) NSMutableArray *otherTeamBuy;//其他团购
@property (nonatomic, retain) NSMutableArray *historyTeamBuy;//浏览记录
//MBProgressHUD
@property (nonatomic, retain) MBProgressHUD *hud;
@property (nonatomic, retain) NSString *listPrice;//原价
@property (nonatomic, retain) NSString *teamPrice;//团购价
@property (nonatomic, retain) NSString *special;//购买须知
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain)GGTTeamBuyDetailModel *head;
@property (nonatomic, retain)GGTSingleBusinessModel *singleBusiness;
@property (nonatomic, retain)NSNumber *busindessID;
@property (nonatomic, retain)GGTTeamBuyDetailModel *otherBuy;
//收藏按钮图片
@property (nonatomic, retain) UIImage *cHeart;
@property (nonatomic ,retain) UIImage *heart;

@property (nonatomic, retain)GGTBusinessModel *business;
//传递商户电话
@property (nonatomic, retain)NSString *str;
@end

@implementation GGTTeamBuyDetailViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
//数组初始化
        self.otherTeamBuy = [NSMutableArray array];
        self.historyTeamBuy = [NSMutableArray array];
        self.reviewArr = [NSMutableArray array];
//收到通知
         NSNotificationCenter *notiCenter = [NSNotificationCenter defaultCenter];
        [notiCenter addObserver:self selector:@selector(receiveNotfication:) name:@"webView" object:nil];
        
        
        NSNotificationCenter *notiCenter1 = [NSNotificationCenter defaultCenter];
        [notiCenter1 addObserver:self selector:@selector(receiveNot:) name:@"pho" object:nil];
    }
    return self;
}
//收到通知后执行的方法

//弹出电话号码
- (void)receiveNot:(NSNotification *)notiob
{
    self.str = notiob.object;
    UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:self.str otherButtonTitles:nil, nil];
    [actionSheet showInView:self.view];

}
//推出webView
- (void)receiveNotfication:(NSNotification *)noti
{
    GGTWebViewController *webVC = [[GGTWebViewController alloc]init];
    webVC.dealId = noti.object;
    [self.navigationController pushViewController:webVC animated:YES];
    [webVC release];
}


//点击电话弹出拨打电话

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex

{
    
    if (buttonIndex == 0) {
    NSString *str = [NSString stringWithFormat:@"tel://%@", self.str];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
    } else {
        
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    //设定收藏按钮
    self.heart = [UIImage imageNamed:@"heart.png"];
    self.cHeart = [UIImage imageNamed:@"cHeart.png"];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:self.heart style:UIBarButtonItemStyleBordered target:self action:@selector(shouChangbuttonClick:)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor redColor];
    self.navigationItem.backBarButtonItem.tintColor = [UIColor blackColor];
    NSMutableArray *dateTemp = [NSMutableArray array];
    GGTDataBaseHandler *hander = [GGTDataBaseHandler shareInstance];
    dateTemp = [hander selectAll];
    //查找数据库 是否属于已经收藏
    BOOL findIt = NO;//在数据库中是否找到
    for (GGTTeamBuyDataModel *search in dateTemp) {
        if ([self.GGTTeamBuyDetail.deal_id isEqualToString: search.deal_id]) {
            findIt = YES;
        }
    }
    if (findIt == YES) {
        self.navigationItem.rightBarButtonItem.image = self.cHeart;
    }
    
    
    self.flag = 0;

    

//获取指定团购信息
    self.number = self.GGTTeamBuyDetail.number;
    self.string = self.GGTTeamBuyDetail.deal_id;
    NSString *url = @"v1/deal/get_single_deal";
    NSString *params = [NSString stringWithFormat:@"deal_id=%@", self.string];
    [[[GGTAppDelegate instance] dpapi] requestWithURL:url paramsString:params delegate:self];
//加载视图
    
    self.tableView = [[UITableView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    //HUB
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.hud.labelText = @"获取团购详情";
    [self.hud setMode:MBProgressHUDModeIndeterminate];
}
//收藏按钮触发时间...
- (void)shouChangbuttonClick:(UINavigationItem *)button
{
    if ([self.navigationItem.rightBarButtonItem.image isEqual:self.heart]) {
        [self.navigationItem.rightBarButtonItem setImage:self.cHeart];
        GGTTeamBuyDataModel *tempModel = [[GGTTeamBuyDataModel alloc]init];
        tempModel.title = self.head.title;
        tempModel.descript = self.head.descript;
        tempModel.current_price = self.head.current_price;
        tempModel.list_price = self.head.list_price;
        tempModel.image = self.head.image;
        tempModel.deal_id = self.head.deal_id;
        tempModel.number = self.head.number;
        GGTDataBaseHandler *handler = [GGTDataBaseHandler shareInstance];
        [handler creatTable];
        [handler insertTeamBuyData:tempModel];
        
    } else {
        [self.navigationItem.rightBarButtonItem setImage:self.heart];
        GGTDataBaseHandler *handler = [GGTDataBaseHandler shareInstance];
        [handler deleteTeamBuyDataLieming:@"deal_id" chaxunzhi:[NSString stringWithFormat:@"'%@'",self.head.deal_id]];
      
        
    }
}
#pragma mark - 豆瓣相关回调函数
//解析数据
//错误方法
- (void)request:(DPRequest *)request didFailWithError:(NSError *)error
{
    //self.resultTextView.contentOffset = CGPointZero;
    NSLog(@"注意参数或地址填写错误:%@",[error description]);
    
}
//正确方法
- (void)request:(DPRequest *)request didFinishLoadingWithResult:(id)result
{
    
    if (self.flag % 4 == 0) {
        self.GGTTeamBuy = result;
        //self.resultTextView.contentOffset = CGPointZero;
        //NSLog(@"%@", request.getURL);
//获取指定商户团购信息
        NSString *url2 = @"v1/deal/get_deals_by_business_id";
        NSString *params2 = [NSString stringWithFormat:@"business_id=%@&city=%@",self.number, [[NSUserDefaults standardUserDefaults] objectForKey:@"cityName"]];
        [[[GGTAppDelegate instance] dpapi] requestWithURL:url2 paramsString:params2 delegate:self];

        NSDictionary *dic = [[result objectForKey:@"deals"]lastObject];
        self.head = [[GGTTeamBuyDetailModel alloc]initWithDictionary:dic];
        self.GGTTeamBuyBusiness = [[[[result objectForKey:@"deals"]lastObject]objectForKey:@"businesses"]lastObject];
        
        
        NSDictionary *dic1 = [[result objectForKey:@"deals"]lastObject];
        GGTBusinessModel *teamBuy = [[GGTBusinessModel alloc]initWithDic:dic1];
        
        
        self.s1 = [teamBuy.details substringFromIndex:5];
        NSRange range = [self.s1 rangeOfString:@"总价值"];
        if (range.location == NSNotFound) {
            self.s1 = [teamBuy.details substringFromIndex:5];
        } else {
            self.s1 = [self.s1 substringToIndex:range.location];
        }
        self.listPrice = [NSString stringWithFormat:@"总价值:%@元", teamBuy.list_price];
        self.teamPrice = [NSString stringWithFormat:@"团购价:%@元", teamBuy.current_price];
        self.special = teamBuy.special_tips;
        
        
    } else if (self.flag % 4 == 1) {
        
        NSMutableArray *arr = [result objectForKey:@"deals"];
        for (NSDictionary *otherDic in arr) {
            GGTTeamBuyDetailModel *otherTeamBuy = [[GGTTeamBuyDetailModel alloc]initWithDictionary:otherDic];
            [self.otherTeamBuy addObject:otherTeamBuy];
        }
        NSString *url3 = @"v1/review/get_recent_reviews";
        NSString *params3 = [NSString stringWithFormat:@"business_id=%@&limit=3", self.number];
        [[[GGTAppDelegate instance] dpapi] requestWithURL:url3 paramsString:params3 delegate:self];
    } else if (self.flag % 4 == 2) {
//获取指定团购的评价信息
        self.GGTTeamBuyReviews = [result objectForKey:@"reviews"];
        for (NSDictionary *dic in self.GGTTeamBuyReviews) {
           GGTTeamBuyReviewModel *review = [[GGTTeamBuyReviewModel alloc]initWithDictionary:dic];
            [self.reviewArr addObject:review];
        }
        
        NSString *url4 = @"v1/business/get_single_business";
        NSString *params4 = [NSString stringWithFormat:@"business_id=%@", self.number];
        [[[GGTAppDelegate instance] dpapi] requestWithURL:url4 paramsString:params4 delegate:self];
    } else if (self.flag % 4 == 3) {
//        获取指定商户信息
        self.GGTTeamBuyBusinessStar = [[result objectForKey:@"businesses"]lastObject];
        self.singleBusiness = [[GGTSingleBusinessModel alloc]initWithDictionary:self.GGTTeamBuyBusinessStar];
    }
    self.flag++;
    [self.tableView reloadData];
    [self.hud hide:YES];
}
#pragma mark - tableView相关回调
//section中有多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 2;
    } else if (section == 1) {
        return 1;
    } else if (section == 2) {
        return [self.reviewArr count];
    } else if (section == 3) {
        return 1;
    } else if (section == 4) {
        return 2;
    } else if (section == 5) {
        return 1;
    } else if (section == 6) {
       return [self.otherTeamBuy count];
    } else {
       return [self.historyTeamBuy count];
    }
}
//cell赋值
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//banner
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            GGTHeadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"aa"];
            if (cell == nil) {
                cell = [[[GGTHeadTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"aa"]autorelease];
            }
            cell.GGTTeamBuyDetail = self.head;
            return cell;
        } else {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"bb"];
            if (cell == nil) {
                cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"bb"]autorelease];
            }
            cell.textLabel.text = self.head.title;
            cell.textLabel.numberOfLines = 0;
            cell.detailTextLabel.text = self.head.descript;
            cell.detailTextLabel.numberOfLines = 0;
            return cell;
        }
        
    } else if (indexPath.section == 1) {
//进度条
        //tableView.allowsSelection = NO;
            GGTReviewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cc"];
            if (cell == nil) {
                cell = [[[GGTReviewTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cc"]autorelease];
            }
        cell.detail = self.singleBusiness;
            return cell;
    } else  if (indexPath.section == 2) {
//用户评论
        GGTTeamBuyDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"review"];
        if (cell == nil) {
            cell = [[[GGTTeamBuyDetailTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"review"]autorelease];
        }
        GGTTeamBuyReviewModel *review = [self.reviewArr objectAtIndex:indexPath.row];
        cell.teamBuyReview = review;
        return cell;
    } else if (indexPath.section == 3) {
//商户信息
                GGTBusinessTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"dd"];
        if (cell == nil) {
            cell = [[[GGTBusinessTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"dd"]autorelease];
        }
        cell.singleBusiness = self.singleBusiness;
        return cell;
    } else if (indexPath.section == 4) {
//团购详情
        if (indexPath.row == 0) {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ee"];
            if (cell == nil) {
                cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"ee"]autorelease];
            }
            cell.textLabel.text = self.s1;
            [cell.textLabel sizeToFit];
            cell.textLabel.numberOfLines = 0;
            return cell;
        } else {

            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ff"];
            if (cell == nil) {
                cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"ff"]autorelease];
            }
            cell.textLabel.text = [NSString stringWithFormat:@"                                  %@", self.teamPrice];
            //cell.textLabel.backgroundColor = [UIColor redColor];
            cell.textLabel.textColor = [UIColor orangeColor];
            cell.detailTextLabel.text = [NSString stringWithFormat:@"                                                      %@", self.listPrice];
            return cell;
            }
    } else if (indexPath.section == 5) {
//购买须知
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"gg"];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"gg"]autorelease];
        }
        cell.textLabel.text = self.special;
        cell.textLabel.numberOfLines = 0;
        return cell;
    } else if (indexPath.section == 6) {
//其他团购
        GGTOtherTeamBuyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"hh"];
        if (cell == nil) {
            cell = [[[GGTOtherTeamBuyTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"hh"]autorelease];
        }
       self.otherBuy = [self.otherTeamBuy objectAtIndex:indexPath.row];
        cell.detailModel = self.otherBuy;
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        return cell;
    } else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ii"];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"ii"]autorelease];
        }
        return cell;
    }
}
//点击cell后执行的方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//商户
    if (indexPath.section == 3) {
        GGTBusinessViewController *businessVC = [[GGTBusinessViewController alloc]init];
        businessVC.businessDetail = self.number;
        [self.navigationController pushViewController:businessVC animated:YES];
    } if (indexPath.section == 6 ) {
//团购
        GGTTeamBuyDetailViewController *detailVC = [[GGTTeamBuyDetailViewController alloc]init];
    
        detailVC.GGTTeamBuyDetail = [self.otherTeamBuy objectAtIndex:indexPath.row];
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}
//section头的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
    } else {
        return 30;
    }
}
//cell的行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return 200;
        } else {
            return 80;
        }
    } else if (indexPath.section == 1) {
        return 80;
    } else if (indexPath.section == 2) {
        return 80;
        
    } else if (indexPath.section == 3) {
        return 60;
    } else if (indexPath.section == 4) {
        if (indexPath.row == 0) {
//自适应文字的高度
            CGRect rect = [self.s1 boundingRectWithSize:CGSizeMake(320, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:19]} context:nil];
            return rect.size.height + 30;
        } else {
            return 80;
        }
    } else if (indexPath.section == 5) {
        CGRect rect = [self.special boundingRectWithSize:CGSizeMake(320, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:19]} context:nil];
        return rect.size.height;
    } else {
        return 60;
    }
}
//有多少section
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 8;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)dealloc
{
    [_GGTTeamBuy release];
    [_GGTTeamBuyBusiness release];
    [_GGTTeamBuyReviews release];
    [_reviewArr release];
    [_s1 release];
    [_special release];
    [_listPrice release];
    [_teamPrice release];
    [_historyTeamBuy release];
    [_otherTeamBuy release];
    [super dealloc];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
